
/*

async function getUser() {
  return await fetch("./1.json")
}

async function m1() {
  const user = await getUser()
  return user
}

async function m2() {
  const user = await m1()
  return user
}

async function m3() {
  const user = await m2()
  return user
}

async function main() {
  const user = await m3()
  console.log(user)
}
*/


/**
 * 消除异步的传染性
 */
function getUser() {
  return  fetch("./1.json")
}

function m1() {
  const user =  getUser()
  return user
}

function m2() {
  const user =  m1()
  return user
}

function m3() {
  const user =  m2()
  return user
}

function main() {
  console.log('main')
  const user =  m3()
  console.log(user)
}

run(main)

function run(func) {
  // 1 改动 fetch
  const oldFetch = window.fetch
  const cache = {
    status: 'pending', // pending | fulfilled | rejected
    value: null,
  }
  function newFetch(...args) {
    if(cache.status === 'fulfilled'){
      return cache.value
    } else if (cache.status === 'rejected'){
      throw cache.value
    }
    
    const p = oldFetch(...args)
      .then(res => res.json())
      .then(data => {
        cache.status = 'fulfilled'
        cache.value = data
      })
      .catch(err => {
        cache.status = 'rejected'
        cache.value = err
      })
    
    throw p
  }
  
  window.fetch = newFetch
  
  // 2 运行 func
  try {
    func()
  } catch (e) {
    if (e instanceof Promise) {
      e.finally(() => {
        window.fetch = newFetch
        func();
        window.fetch = oldFetch
      })
    }
  }
  
  
  // 3 改回fetch
  window.fetch = oldFetch
}
